﻿using System;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using YiSha.Util;
using YiSha.Util.Extension;
using YiSha.Util.Model;
using YiSha.Data;
using YiSha.Data.Repository;
using YiSha.Entity.YiDongYuan;
using YiSha.Model.Param.YiDongYuan;

namespace YiSha.Service.YiDongYuan
{
    /// <summary>
    /// 创 建：admin
    /// 日 期：2021-06-16 08:31
    /// 描 述：机械备案申报服务类
    /// </summary>
    public class MechanicsApplyService : RepositoryFactory
    {
        #region 获取数据

        public async Task<List<RegionReportEntity>> GetRegionList(string type)
        {
            var strSql = new StringBuilder();
            strSql.Append("SELECT Region as RegionName,COUNT(*) as RegionValue FROM mechanicsapply ");
            switch (type)
            {
                case "month":
                    strSql.Append(" WHERE DATE_FORMAT(AuditTime, '%m')=DATE_FORMAT(NOW(),'%m') ");
                    break;

                case "today":
                    strSql.Append(" WHERE DATE_FORMAT(AuditTime, '%d')=DATE_FORMAT(NOW(),'%d') ");
                    break;
            }
            strSql.Append(" GROUP BY region ORDER BY COUNT(*) DESC");
            var list = await this.BaseRepository().FindList<RegionReportEntity>(strSql.ToString());
            return list.ToList();
        }

        public async Task<List<RegionReportEntity>> GetRegionListByDictType(string region)
        {
            var strSql = "SELECT DictKey AS ReportValue,DictValue AS RegionName FROM sysdatadictdetail WHERE DictType='" + region + "' ORDER BY DictKey";
            var list = await this.BaseRepository().FindList<RegionReportEntity>(strSql);
            return list.ToList();
        }

        public async Task<List<MechanicsApplyEntity>> GetList(MechanicsApplyListParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList();
        }

        public async Task<List<MechanicsApplyEntity>> GetPageList(MechanicsApplyListParam param, Pagination pagination)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression, pagination);
            return list.ToList();
        }

        public async Task<MechanicsApplyEntity> GetEntity(long id)
        {
            return await this.BaseRepository().FindEntity<MechanicsApplyEntity>(id);
        }

        #endregion 获取数据

        #region 提交数据

        public async Task SaveForm(MechanicsApplyEntity entity)
        {
            var db = this.BaseRepository();
            if (entity.Id.IsNullOrZero())
            {
                await entity.Create();
                await this.BaseRepository().Insert(entity);
            }
            else
            {
                await this.BaseRepository().Update(entity);
            }
        }

        public async Task DeleteForm(string ids)
        {
            long[] idArr = TextHelper.SplitToArray<long>(ids, ',');
            await this.BaseRepository().Delete<MechanicsApplyEntity>(idArr);
        }

        public async Task<List<MechanicsApplyEntity>> GetListByUserId(long userId)
        {
            var expression = LinqExtensions.True<MechanicsApplyEntity>();
            expression = expression.And(t => t.BaseCreatorId == userId);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList(); ;
        }

        public async Task SaveAudit(string id, int auditStatus, string auditReason, string code, long? auditUser, long? detectionUser)
        {
            await this.BaseRepository().BeginTrans();
            try
            {
                var entity = await this.GetEntity(id.ParseToLong());
                if (auditStatus == 1)
                {
                    var mechanics = new MechanicsEntity();
                    await mechanics.Create();
                    mechanics.HuanBaoCode = code;
                    mechanics.JXDJLX = entity.JXDJLX;
                    mechanics.JXLB = entity.JXLB;
                    mechanics.Region = entity.Region;
                    mechanics.PFJD = entity.PFJD;
                    mechanics.OwnerTel = entity.OwnerTel;
                    mechanics.OwnerAddr = entity.OwnerAddr;
                    mechanics.OwnerCardNo = entity.OwnerCardNo;
                    mechanics.OwnerCard_Pic = entity.OwnerCard_pic;
                    mechanics.OwnerName = entity.OwnerName;
                    await this.BaseRepository().Insert(mechanics);
                    entity.MechanicsId = await CreateDetectionTask(entity.Region, mechanics, detectionUser);
                    await this.BaseRepository().Delete<SparePlateEntity>(t => t.HuanBaoCode == code);
                }
                else if (entity.AuditStatus == 9)
                {
                    entity.AuditReason = auditReason;
                }
                entity.AuditTime = DateTime.Now;
                entity.AuditUserId = auditUser;
                entity.AuditStatus = auditStatus;

                await this.BaseRepository().Update(entity);
                await this.BaseRepository().CommitTrans();
            }
            catch (Exception)
            {
                await this.BaseRepository().RollbackTrans();
                throw;
            }
        }

        private async Task<long> CreateDetectionTask(string region, MechanicsEntity mechanics, long? detectionUser)
        {
            var dmEntity = new DetectionMechanicsEntity();
            dmEntity.CopyFromMechanics(mechanics);
            await dmEntity.Create();
            await this.BaseRepository().Insert(dmEntity);
            var task = new DetectionTaskEntity()
            {
                DetectionType = 0,
                DetectionStatus = 0,
                DetectionUserId = detectionUser,
                DetectionTime = null,
                AuditStatus = -1,
                AuditTime = null,
                HuanBaoCode = dmEntity.HuanBaoCode,
                MechanicsId = dmEntity.Id,
                Region = region,
            };
            await task.Create();
            await this.BaseRepository().Insert(task);
            return dmEntity.Id.Value;
        }

        #endregion 提交数据

        #region 私有方法

        private Expression<Func<MechanicsApplyEntity, bool>> ListFilter(MechanicsApplyListParam param)
        {
            var expression = LinqExtensions.True<MechanicsApplyEntity>();
            if (param != null)
            {
                if (param.auditStatus != -1)
                    expression = expression.And(t => t.AuditStatus == param.auditStatus);
                if (!param.region.IsNullOrEmpty() && !param.region.Equals("运城市"))
                    expression = expression.And(t => t.Region == param.region);
                if (!param.keywords.IsNullOrEmpty())
                {
                    expression = expression.And(t => t.OwnerName.Contains(param.keywords) || t.OwnerTel.Contains(param.keywords));
                }
                if (!param.Ids.IsNullOrEmpty())
                {
                    long[] idList = TextHelper.SplitToArray<long>(param.Ids, ',');
                    expression = expression.And(t => idList.Contains(t.Id.Value));
                }
            }
            return expression;
        }

        #endregion 私有方法
    }
}
